<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

Loader::loadClass('Model');

class RlModel extends Model
{
    protected $_table = 'admin';

    const USERID = 'a';
    const FORCE_QQ = 'b';
    const ISFREE = 'c';
    const GROUPID = 'd';
    const ISSTOP = 'e';
    
    public function addAdmin($data) {
        return $this->insert($data);
    }
    
    public function getAdmin($where) {
        return $this->getOne($where);
    }
    
    public function getAdmins($where = '') {
        return $this->select($where, '*', '', '', '', 'userid');
    }
    
    public function deleteAdmin($where) {
        return $this->delete($where);
    }
    
    public function updateAdmin($data, $where) {
        return $this->update($data, $where);
    }
    
    public function listAdmins($where, $page = 1, $perpage = 30, $order = 'userid DESC') {
        Loader::loadClass('Page');
        return $this->listInfo($where, $page, $perpage, $order, '');
    }
    
    public function login($data) {
        if(!is_username($data['username'])) {
            return false;
        }

        if(!is_password($data['password'])) {
            return false;
        }

        $r = $this->getOne(array('username' => $data['username']));
        if(!$r) {
            return false;
        }
        
        $password = password($data['password'], $r['salt']);
        if($password != $r['password']) {
            return false;
        }
        
        $this->setCookieSession($r);
        return true;
    }

    public function logout() {
        session_destroy();
        setcookie(session_name(), '');
    }
    
    public function setCookieSession($member) {
        //sessions
        $_SESSION[RlModel::USERID] = $member['userid'];
        $_SESSION[RlModel::FORCE_QQ] = $member['force_qq'];
        $_SESSION[RlModel::ISFREE] = $member['isfree'];
        $_SESSION[RlModel::GROUPID] = $member['groupid'];
        $_SESSION[RlModel::ISSTOP] = $member['isstop'];
        
        //cookies
        set_cookie('a_username', urlencode($member['username']));
        $groups = get_group_cache();
        set_cookie('a_groupname', urlencode($groups[$member['groupid']]['groupname']));
        set_cookie('a_ip', $member['ip']);
        set_cookie('a_lastvist', date('Y-m-d    H:i:s', $member['lastvist']));
        
        //更新
        $data = array(
            'ip' => IP,
            'lastvist' => SYS_TIME
        );
        
        $this->updateAdmin($data, array('userid' => $member['userid']));
    }
    
    public function qqLogout() {
        unset($_SESSION['qq']);
        unset($_SESSION['qq_openid']);
    }
}